package main

import api.ItemApi
import api.MemberApi
import api.TaskApi
import api.TopicApi
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import interceptor.AuthorizationInterceptor
import interceptor.LogInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author BX-Gin
 * @since 2024/6/6 上午11:45
 * @param authorization 令牌
 * @param debug 是否为debug模式（打印日志）
 * @property client 客户端
 * @property retrofit Retrofit!
 * @property memberApi 用户相关API
 * @property itemApi 道具相关API
 * @property taskApi 任务相关API
 * @property topicApi 主题相关API
 * @constructor
 */
class Gf2BbsRetrofit(private val authorization: String, private val debug: Boolean = false) {

    private val client = OkHttpClient.Builder()
        .addInterceptor(AuthorizationInterceptor(authorization))
        .callTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .also { if (debug) it.addInterceptor(LogInterceptor()) }
        .build()

    private val retrofit = Retrofit.Builder()
        .client(client)
        .baseUrl(API)
        .addConverterFactory(JacksonConverterFactory.create(MAPPER))
        .build()
    val memberApi: MemberApi = retrofit.create(MemberApi::class.java)
    val itemApi: ItemApi = retrofit.create(ItemApi::class.java)
    val taskApi: TaskApi = retrofit.create(TaskApi::class.java)
    val topicApi: TopicApi = retrofit.create(TopicApi::class.java)

    companion object {
        const val API = "https://gf2-bbs-api.sunborngame.com/"

        val MAPPER: ObjectMapper = ObjectMapper()
            .enable(SerializationFeature.INDENT_OUTPUT)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)

        fun println(obj: Any?) {
            println(MAPPER.writeValueAsString(obj))
        }
    }
}